// http://code.google.com/chrome/extensions/options.html

var options = {
	url: {
		feed: ti.data.get('feed'),
		blog: ti.data.get('blog')
	},
	backColor: ti.data.get('color'),
	title: ti.data.get('title'),
	save: function() {
		ti.data.set('feed', this.url.feed);
		ti.data.set('blog', this.url.blog);
		ti.data.set('title', this.title);
		ti.data.set('color', this.backColor);
	},
	parse: function(url, color, callback) {
		var xhr = new XMLHttpRequest();
		xhr.onreadystatechange = function(data) {
			if (xhr.readyState == 4) {
				if (xhr.status == 200) {
					var message = null;
					options.backColor = color;

					if (xhr.responseXML) {
						// the url was the feed
						options.url.feed = normalizeFeed(url);
						
						// blog url
						var links = xhr.responseXML.getElementsByTagName('link');
						for (var i = 0; i < links.length; i++) {
							if (links[i].getAttribute('rel') == 'alternate') {
								options.url.blog = links[i].getAttribute('href');
								break;
							}
						}
						// title
						var title = xhr.responseXML.getElementsByTagName('title');
						if (title && title.length > 0) {
							options.title = title[0].textContent;
						}
						options.save();
					} else if (xhr.responseText) {
						options.url.blog = url;
						var re = /<link[^>]+rel=['"]alternate['"][^>]+>/gi;
						var href = /href=(["'])([^\1]+)\1/i;
						var match;
						
						while ((match = re.exec(xhr.responseText)) != null) {
							if (/type=["']application\/atom\+xml/.test(match[0])) {
								options.url.feed = normalizeFeed(href.exec(match[0])[2]);
								break;
							} else if (/type=["']application\/rss\+xml/.test(match[0])) {
								options.url.feed = normalizeFeed(href.exec(match[0])[2]);
							}
						}
						// title
						var match = /<title>([^<]+)<\/title>/.exec(xhr.responseText);
						if (match) { options.title = match[1]; }
						
						options.save();
					} else {
						message = url + ' returned nothing';
					}
				} else {
					message = 'Attempt to load ' + url + ' returned ' + xhr.status;
				}
				callback(message);
			}
		}
		console.log('loading ' + url);
		xhr.open('GET', url, true);
		xhr.send();
	}
}
function normalizeFeed(url) {
	return url
		+ (/\?/.test(url) ? '&' : '?')
		+ 'max-results=100&published-min=2007-05-03T23%3A59%3A59-05%3A00';
}


